package com.weishi.project.sport.movement.thread;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.project.sport.movement.selection.MovementSelection;
import com.weishi.project.sport.movement.vo.TrainingReportBean;
import com.weishi.project.sport.movement.vo.TrainingVO;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 增删改
 */
@Component
public class MovementRunnable implements Runnable {


    /**
     * redis 数据库
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 训练成绩 接口
     */
    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    /**
     * 运动员接口
     */
    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 测功仪数据接口
     */
    @Autowired
    private IDynamometerService dynamometerService;

    /**
     * 测功仪成绩排名 接口
     */
    @Autowired
    private IDynamometerRankingService dynamometerRankingService;

    /**
     * 训练成绩表 接口
     */
    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    /**
     * 训练课接口
     */
    @Autowired
    private ITrainingDayService trainingDayService;

    @Autowired
    private ITrainingGroupService trainingGroupService;

    /**
     * 分段成绩 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;


    private Map<Integer, Map<Integer, Integer>> group_channel = new HashMap<>();

    @Scheduled(cron = "0 0/3 * * * ?")  // 每 3 分钟执行一次
    //@Scheduled(cron = "0 0 */1 * * ?")
    protected void clearGroup() {
        group_channel.clear();
    }

    private Integer getChannelId(TrainingReportBean trainingDetails, Integer sportId) {
        Map<Integer, Integer> sport_channel_id = group_channel.get(trainingDetails.getGroupId());
        if (sport_channel_id == null) {
            sport_channel_id = new HashMap<>();
            group_channel.put(trainingDetails.getGroupId(), sport_channel_id);
        }
        Integer channelId = sport_channel_id.get(sportId);
        if (channelId == null) {
            // 根据 小组id 和用户 id 查询有没有在训练
            List<TrainingVO> trainingVO = trainingGroupChannelService.getOneTrainingVO(trainingDetails.getGroupId(), trainingDetails.getUserId());
            if (trainingVO != null && trainingVO.size() > 0) {
                channelId = trainingVO.get(0).getChannelId();
            } else {
                //TODO 创建航道
                TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
                trainingGroupChannel.setCtime(new Date());
                trainingGroupChannel.setGroupId(trainingDetails.getGroupId());
                trainingGroupChannel.setAchievement("汇总中请下划刷新");
                trainingGroupChannelService.save(trainingGroupChannel);

                TrainingAchievement trainingAchievement = new TrainingAchievement();
                trainingAchievement.setCtime(new Date());
                trainingAchievement.setChannelId(trainingGroupChannel.getId());
                trainingAchievement.setWeekId(trainingDayService.getById(trainingDetails.getTrainingDayId()).getWeekId());
                trainingAchievement.setSportsmanId(sportId);
                trainingAchievement.setGroupId(trainingDetails.getGroupId());
                trainingAchievement.setTrainingMode(trainingDetails.getTrainingMode());
                trainingAchievement.setTrainingDayId(trainingDetails.getTrainingDayId());
                trainingAchievementService.save(trainingAchievement);

                channelId = trainingGroupChannel.getId();
                trainingDetails.setAchievementId(trainingAchievement.getId());

            }
            sport_channel_id.put(sportId, channelId);
        }
        return channelId;
    }


    @Override
    public void run() {
        /**
         * 线程池高并发，使用同步线程做处理
         */

        /**
         * 运动员端--运动模块--新增心率
         */
        if (MovementSelection.getValue().equals("addHeartRate")) {


            /**
             * 运动员端--新增测功仪数据
             */
        } else if (MovementSelection.getValue().equals("MovementServiceImpl_addDynamometer")) {
            try {
                TrainingReportBean trainingDetails = (TrainingReportBean) redisTemplate.boundListOps("MovementServiceImpl_addDynamometer_trainingReportBean").rightPop();

                int channelId = getChannelId(trainingDetails, trainingDetails.getUserId());
                trainingDetails.setChannelId(channelId);

                // 把心率信息实时放到 Redis 缓存中
                sportsmanService.setHeartCount(trainingDetails.getUserId(), Integer.parseInt(trainingDetails.getHeartRate()));

                Sportsman sportsman = sportsmanService.qrySportsmanByCache(trainingDetails.getUserId());
                // 新增测功仪成绩数据
                DynamometerRanking dynamometerRanking = new DynamometerRanking();
                StringUtils.copyProperties(trainingDetails, dynamometerRanking);
                // 成绩转换 格式为 00:00:00.000
                Long achievement2 = StringUtils.turnSecond(dynamometerRanking.getLengthTime());
                dynamometerRanking.setLengthTime(StringUtils.millisecondRotationTime(achievement2));
                dynamometerRanking.setCtime(new Date());
                dynamometerRanking.setSportsmanId(Long.parseLong(trainingDetails.getUserId().toString()));
                dynamometerRanking.setSex(Long.parseLong(sportsman.getSex().toString()));
                dynamometerRanking.setSportsmanName(sportsman.getName());
                dynamometerRanking.setGroupId(Long.parseLong(trainingDetails.getGroupId().toString()));
                dynamometerRanking.setTimeMillisecond(StringUtils.turnSecond(dynamometerRanking.getLengthTime()));

                Dynamometer dynamometer = new Dynamometer();
                if (trainingDetails.getMileage() > 0.0) {
                    //放入缓存
                    redisTemplate.boundHashOps("dynamometerRanking" + dynamometerRanking.getGroupId().toString()).put(dynamometerRanking.getGroupId().toString() + trainingDetails.getUserId().toString(), dynamometerRanking);
                    StringUtils.copyProperties(trainingDetails, dynamometer);
                    dynamometer.setCtime(new Date());
                    dynamometer.setSportsmanId(trainingDetails.getUserId());
                    dynamometer.setSex(sportsman.getSex());
                    dynamometer.setSportsmanName(sportsman.getName());
                    // 成绩转换 格式为 00:00:00.000
                    Long achievement = StringUtils.turnSecond(trainingDetails.getLengthTime());
                    dynamometer.setLengthTime(StringUtils.millisecondRotationTime(achievement));
                    dynamometerService.save(dynamometer);
                }

                // 判断是否点击结束训练
                if (trainingDetails.getIsEnd() == 0) {

                    List<Map<String, Object>> jsondate = new ArrayList<>();
                    // 汇总测功仪历史数据
                    List<Dynamometer> dynamometerList = dynamometerService
                            .list(Wrappers.<Dynamometer>lambdaQuery()
                                    .eq(Dynamometer::getSportsmanId, trainingDetails.getUserId())
                                    .eq(Dynamometer::getGroupId, trainingDetails.getGroupId()));

                    if (dynamometerList.size() == 0) {
                        TrainingGroupChannel trainingGroupChannel1 = trainingGroupChannelService.getById(trainingDetails.getChannelId());
                        trainingGroupChannel1.setAchievement("");
                        trainingGroupChannel1.setId(trainingDetails.getChannelId());
                        trainingGroupChannelService.updateById(trainingGroupChannel1);
                    }

                    if (dynamometerList.size() > 0) dynamometerList.forEach(d -> {
                        Map<String, Object> temp = new HashMap<>();
                        temp.put("mileage", d.getMileage());
                        temp.put("propellerFrequency", d.getPropellerFrequency());
                        temp.put("heartRate", d.getHeartRate() == null ? 0 : d.getHeartRate());
                        temp.put("lengthTime", d.getLengthTime());
                        temp.put("speed", d.getSpeed() == null ? 0.0 : d.getSpeed());
                        temp.put("power", d.getPower());
                        temp.put("watt", d.getWatt());
                        temp.put("peakForce", d.getPeakForce() == null ? 0.0 : d.getPeakForce());
                        temp.put("averageForce", d.getAverageForce() == null ? 0.0 : d.getAverageForce());
                        temp.put("pulpNumber", d.getPulpNumber() == null ? 0 : dynamometer.getPulpNumber());
                        temp.put("trainingMode", d.getTrainingMode() == null ? 0.0 : dynamometer.getTrainingMode());
                        temp.put("segmentNumber", d.getSegmentNumber() == null ? 0.0 : d.getSegmentNumber());
                        jsondate.add(temp);
                    });
                    dynamometer.setCtime(new Date());
                    dynamometer.setSportsmanId(trainingDetails.getUserId());
                    dynamometer.setSex(sportsman.getSex());
                    dynamometer.setSportsmanName(sportsman.getName());
                    dynamometerService.save(dynamometer);

                    List<DynamometerSubsection> dynamometerSubsections = dynamometerSubsectionService
                            .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                                    .eq(DynamometerSubsection::getSportsmanId, trainingDetails.getUserId())
                                    .eq(DynamometerSubsection::getGroupId, trainingDetails.getGroupId()));

                    //数据纠错
                    correctDynamometerSubsection(dynamometerSubsections, dynamometerRanking);
                    dynamometerSubsections = dynamometerSubsectionService
                            .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                                    .eq(DynamometerSubsection::getSportsmanId, trainingDetails.getUserId())
                                    .eq(DynamometerSubsection::getGroupId, trainingDetails.getGroupId())
                                    .orderByAsc(DynamometerSubsection::getSegmentNumber));

                    // 计算瓦特
                    Integer avgWatt = 0;
                    Long avgPower = 0L;
                    Double avgPeakForce = 0.0;
                    Double avgForce = 0.0;
                    Double propellerFrequency = 0.0;
                    int size = dynamometerSubsections.size();
                    for (DynamometerSubsection dynamometerSubsection : dynamometerSubsections) {
                        if (!dynamometerSubsection.getWatt().equals("")) {
                            avgWatt += Integer.parseInt(dynamometerSubsection.getWatt());
                        }
                        if (!dynamometerSubsection.getPower().equals("")) {
                            avgPower += StringUtils.turnSecond(dynamometerSubsection.getPower());
                        }
                        avgPeakForce += dynamometerSubsection.getPeakForce();
                        avgForce += dynamometerSubsection.getAverageForce();
                        propellerFrequency += Double.parseDouble(dynamometerSubsection.getPropellerFrequency());
                    }

                    // 更新数据  DynamometerRanking
                    DynamometerRanking dynamometerRankings = (DynamometerRanking) redisTemplate.boundHashOps("dynamometerRanking" + dynamometerRanking.getGroupId().toString()).get(trainingDetails.getGroupId().toString() + trainingDetails.getUserId().toString());
                    if (StringUtils.isNotNull(dynamometerRankings)) {
                        DynamometerRanking dynamometerRanking1 = new DynamometerRanking();
                        StringUtils.copyProperties(dynamometerRankings, dynamometerRanking1);
                        Double propellerFrequencys = propellerFrequency / size;
                        dynamometerRanking1.setPropellerFrequency(propellerFrequencys.toString());
                        // 功率转换 格式为 00:00:00.000
                        Long power = StringUtils.turnSecond(dynamometerRanking1.getPower());
                        dynamometerRanking1.setPower(StringUtils.millisecondRotationTime(power));
                        dynamometerRankingService.save(dynamometerRanking1);
                        redisTemplate.boundHashOps("dynamometerRanking" + dynamometerRankings.getGroupId().toString()).delete(trainingDetails.getGroupId().toString() + trainingDetails.getUserId().toString());
                    }

                    avgWatt = size == 0 ? 0 : avgWatt / size;
                    avgPower = size == 0 ? 0 : avgPower / size;
                    avgPeakForce = size == 0 ? 0.0 : avgPeakForce / size;
                    avgForce = size == 0 ? 0.0 : avgForce / size;
                    // 更新教练员端的成绩 直接新增
                    TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
                    trainingGroupChannel.setPropellerFrequency(dynamometer.getPropellerFrequency());
                    trainingGroupChannel.setWatt(String.valueOf(avgWatt));
                    trainingGroupChannel.setPower(StringUtils.millisecondRotationTime(avgPower));
                    if (StringUtils.isNotNull(dynamometer.getMileage())
                            && dynamometer.getMileage() > 0.0) {
                        trainingGroupChannel.setRowingKilometers(dynamometer.getMileage().intValue());

                        // 速度
                        Long achievement = StringUtils.turnSecond(dynamometer.getLengthTime());
                        trainingGroupChannel.setSpeed(dynamometer.getMileage() / achievement);
                    }
                    if (StringUtils.isNotNull(dynamometer.getSegmentNumber())
                            && dynamometer.getSegmentNumber() > 0) {
                        trainingGroupChannel.setStages(dynamometer.getSegmentNumber() + 1);
                    }
                    // 浆数
                    trainingGroupChannel.setPulpNumber(dynamometerRanking.getPulpNumber().intValue());
                    // 峰力
                    trainingGroupChannel.setPeakForce(dynamometerRanking.getPeakForce().toString());
                    // 均力
                    trainingGroupChannel.setAverageForce(dynamometerRanking.getAverageForce().toString());

                    if (trainingDetails.getTrainingMode() == 0) {
                        trainingGroupChannel.setAchievement(dynamometer.getLengthTime());
                        // 分段成绩
                        String segmentedTiming = "";
                        for (int i = 0; i < dynamometerSubsections.size(); i++) {
                            segmentedTiming += dynamometerSubsections.get(i).getLengthTime() + " ";
                        }
                        if (segmentedTiming.length() > 1)
                            trainingGroupChannel.setSegmentedTiming(segmentedTiming.substring(0, segmentedTiming.length() - 1));
                    } else {
                        trainingGroupChannel.setAchievement(dynamometer.getMileage().toString());
                        // 分段成绩
                        String segmentedTiming = "";
                        for (int i = 0; i < dynamometerSubsections.size(); i++) {
                            segmentedTiming += dynamometerSubsections.get(i).getMileage().toString() + " ";
                        }
                        trainingGroupChannel.setSegmentedTiming(segmentedTiming.substring(0, segmentedTiming.length() - 1));

                        // 如果是时间手段，那么就从课程里面查询出 时间，然后 set 进航道里
                        trainingGroupChannel.setRowingClassHour(trainingDayService.getById(trainingDetails.getTrainingDayId()).getClassHour());
                    }
                    trainingGroupChannel.setGroupId(trainingDetails.getGroupId());
                    trainingGroupChannel.setCtime(new Date());
                    trainingGroupChannel.setId(trainingDetails.getChannelId());
                    trainingGroupChannelService.updateById(trainingGroupChannel);

                    //同步陆上滑行公里数
                    TrainingGroup trainingGroup = new TrainingGroup();
                    trainingGroup.setId(trainingDetails.getGroupId());
                    if (StringUtils.isNotNull(trainingGroupChannel.getRowingKilometers())
                            && trainingGroupChannel.getRowingKilometers() > 0) {
                        trainingGroup.setKilometer(trainingGroupChannel.getRowingKilometers());
                    }
                    trainingGroupService.updateById(trainingGroup);
                    trainingDayService.aggregateData(trainingDetails.getTrainingDayId());

                    /**
                     * 新增数据到 成绩表
                     */
                    TrainingAchievement trainingAchievement = new TrainingAchievement();
                    trainingAchievement.setChannelId(trainingGroupChannel.getId());
                    trainingAchievement.setGroupId(trainingDetails.getGroupId());
                    trainingAchievement.setTrainingDayId(trainingDetails.getTrainingDayId());
                    trainingAchievement.setSportsmanId(trainingDetails.getUserId());
                    trainingAchievement.setSportsmanName(sportsman.getName());
                    trainingAchievement.setWeekId(trainingDayService.getById(trainingDetails.getTrainingDayId()).getWeekId());
                    trainingAchievement.setCtime(new Date());
                    trainingAchievement.setId(trainingDetails.getAchievementId());
                    trainingAchievementService.updateById(trainingAchievement);

                    double kilometers = 0;
                    long time = 0;
                    for (DynamometerSubsection p : dynamometerSubsections) {
                        if (p.getSegmentNumber() == 1) {
                            p.setJsonData(JSONArray.toJSONString(jsondate));
                        }
                        //分段速度
                        kilometers = p.getMileage() - kilometers;
                        time =  StringUtils.turnSecond(p.getLengthTime())-time;
                        p.setSpeed(kilometers / time);

                        p.setChannelId(trainingGroupChannel.getId());
                        dynamometerSubsectionService.updateById(p);
                    }
                }


            } catch (Exception e) {
                e.printStackTrace();
            }


            /**
             * 运动员端--新增测功仪数据 结束
             */

        } else {

        }
    }

    /**
     * mbn
     * 纠正分段数据（ps:当前版本测功仪不稳定，容易掉段）
     */
    private List<DynamometerSubsection> correctDynamometerSubsection(List<DynamometerSubsection> dynamometerSubsections, DynamometerRanking dynamometerRanking) {
        Map<Integer, DynamometerSubsection> segmentNumbers = new HashMap<>();
        List<DynamometerSubsection> retList = new ArrayList<>();
        try {
            int flag = 1;
            int tranningMode = dynamometerRanking.getTrainingMode().intValue();
            int clearanceDistance = 0;//间隙距离
            long clearanceTime = 0;//间隙时间
            DynamometerSubsection temp = null;
            List<Dynamometer> dynamometerList = dynamometerService
                    .list(Wrappers.<Dynamometer>lambdaQuery()
                            .eq(Dynamometer::getSportsmanId, dynamometerRanking.getSportsmanId().intValue())
                            .eq(Dynamometer::getGroupId, dynamometerRanking.getGroupId().intValue()));

            //没有分段，新增一个分段，与总成绩一样
            if (dynamometerSubsections == null || dynamometerSubsections.size() == 0) {
                temp = new DynamometerSubsection();
                temp.setMileage(dynamometerRanking.getMileage());
                temp.setPropellerFrequency(dynamometerRanking.getPropellerFrequency());
                temp.setHeartRate(dynamometerRanking.getHeartRate().intValue());
                temp.setLengthTime(dynamometerRanking.getLengthTime());
                double speed = dynamometerRanking.getMileage() / (DateUtils.getLongTime(dynamometerRanking.getLengthTime()) / 1000.0);
                temp.setSpeed(speed);

                temp.setPower(dynamometerRanking.getPower());

                temp.setWatt(dynamometerRanking.getWatt());
                temp.setPeakForce(dynamometerRanking.getPeakForce());
                temp.setAverageForce(dynamometerRanking.getAverageForce().doubleValue());
                temp.setPulpNumber(dynamometerRanking.getPulpNumber().intValue());
                temp.setGroupId(dynamometerRanking.getGroupId().intValue());
                temp.setSportsmanId(dynamometerRanking.getSportsmanId().intValue());
                temp.setTrainingDayId(dynamometerRanking.getTrainingDayId().intValue());
                temp.setGroupName(dynamometerRanking.getGroupName());
                temp.setTrainingMode(dynamometerRanking.getTrainingMode().intValue());
                temp.setSegmentNumber(1);
                temp.setCtime(new Date());
                dynamometerSubsectionService.save(temp);
            } else {
                //中间掉段
                for (DynamometerSubsection ds : dynamometerSubsections) {
                    temp = ds;
                    int index = temp.getSegmentNumber();
                    segmentNumbers.put(index, temp);
                    retList.add(ds);

                    int endDistance = (int) Math.abs((temp.getMileage() / 100));
                    clearanceDistance = endDistance / index;
                    long endTime = Math.abs(StringUtils.turnSecond(temp.getLengthTime()) / 10000);
                    clearanceTime = endTime / index;

                    if (index - flag++ > 0) {
                        while (index - flag >= 0) {
                            endDistance = (int) Math.abs((temp.getMileage() / 100));
                            endTime = Math.abs(StringUtils.turnSecond(temp.getLengthTime()) / 10000);
                            DynamometerSubsection ddTemp;
                            if (tranningMode == 0) {
                                ddTemp = calculationDynamometerSubsection(dynamometerList, (endDistance - clearanceDistance * 2) * 100, (endDistance - clearanceDistance) * 100);
                            } else {
                                ddTemp = calculationDynamometerSubsection(dynamometerList, (endTime - clearanceTime * 2) * 10000, (endTime - clearanceTime) * 10000);
                            }
                            if (ddTemp == null && segmentNumbers.get(flag - 1) != null) {
                                continue;
                            }
                            ddTemp.setGroupId(ds.getGroupId());
                            ddTemp.setSportsmanId(ds.getSportsmanId());
                            ddTemp.setTrainingDayId(ds.getTrainingDayId());
                            ddTemp.setGroupName(ds.getGroupName());
                            ddTemp.setTrainingMode(ds.getTrainingMode());
                            ddTemp.setSegmentNumber(flag - 1);
                            ddTemp.setCtime(new Date());
                            segmentNumbers.put(flag, ddTemp);
                            dynamometerSubsectionService.save(ddTemp);
                            flag++;
                            temp = ddTemp;
                            retList.add(ddTemp);
                        }
                    }
                }

                //后面掉段
                int lastMileage = (int) Math.abs((dynamometerRanking.getMileage() / 100));
                long lastTime = Math.abs(StringUtils.turnSecond(dynamometerRanking.getLengthTime()) / 10000);
                if (lastMileage > 0 && lastTime > 0L) {
                    int count = tranningMode == 0 ? lastMileage / clearanceDistance : (int) (lastTime / clearanceTime);
                    if (count - (flag - 1) >= 0) {
                        //最小分段距离100m 最小分段时间20S
                        while (true && lastMileage > 0 && lastTime > 0) {
                            int startDistance = (int) Math.abs((temp.getMileage() / 100));
                            long startTime = Math.abs(StringUtils.turnSecond(temp.getLengthTime()) / 10000);
                            DynamometerSubsection ddTemp;
                            if (tranningMode == 0 && (lastMileage - startDistance) >= 1) {
                                ddTemp = calculationDynamometerSubsection(dynamometerList, startDistance * 100, (startDistance + clearanceDistance) * 100);
                            } else if (tranningMode == 1 && (lastTime - startTime) >= 2) {
                                ddTemp = calculationDynamometerSubsection(dynamometerList, startTime * 10000, (startTime + clearanceTime) * 10000);
                            } else {
                                break;
                            }
                            if (ddTemp == null && segmentNumbers.get(flag - 1) != null) {
                                continue;
                            }
                            ddTemp.setGroupId(dynamometerRanking.getGroupId().intValue());
                            ddTemp.setSportsmanId(dynamometerRanking.getSportsmanId().intValue());
                            ddTemp.setTrainingDayId(dynamometerRanking.getTrainingDayId().intValue());
                            ddTemp.setGroupName(dynamometerRanking.getGroupName());
                            ddTemp.setTrainingMode(dynamometerRanking.getTrainingMode().intValue());
                            ddTemp.setSegmentNumber(flag - 1);
                            ddTemp.setCtime(new Date());
                            segmentNumbers.put(flag, ddTemp);
                            dynamometerSubsectionService.save(ddTemp);
                            flag++;
                            temp = ddTemp;
                            retList.add(ddTemp);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retList;
    }


    /**
     * 根据实时数据计算出分段(时间手段)
     *
     * @param list
     * @param endTime
     * @return
     */
    private DynamometerSubsection calculationDynamometerSubsection(List<Dynamometer> list, long startTime, long endTime) {
        DynamometerSubsection ds = null;
        double mileage = 0.0;//里程
        int propellerFrequencyTotal = 0;//浆频
        int heartRateTotal = 0;//心率
        long lengthTime = 0;//时长
        long powerTotal = 0;//功率
        long firstTime = 0;//第一个有效的点时间
        double firstDistance = 0;//第一个有效的点距离
        int wattTotal = 0;//瓦特
        double peakForceTotal = 0;//峰力
        double averageForceTotal = 0;//均力
        int pulpNumber = 0;//浆数
        int size = 0;
        for (Dynamometer dynamometer : list) {
            if (StringUtils.isEmpty(dynamometer.getPropellerFrequency()) || dynamometer.getPropellerFrequency().equals("0")) {
                continue;
            }
            long tishTime = StringUtils.turnSecond(dynamometer.getLengthTime());
            if (tishTime >= startTime && tishTime <= endTime) {
                if (firstDistance == 0) {
                    firstDistance = dynamometer.getMileage();
                    firstTime = tishTime;
                }
                size++;
                mileage = dynamometer.getMileage();
                propellerFrequencyTotal += Integer.parseInt(dynamometer.getPropellerFrequency());
                heartRateTotal += dynamometer.getHeartRate();
                lengthTime = tishTime;
                powerTotal += StringUtils.turnSecond(dynamometer.getPower());
                wattTotal += Integer.parseInt(dynamometer.getWatt());
                peakForceTotal += dynamometer.getPeakForce();
                averageForceTotal += dynamometer.getAverageForce();
                pulpNumber = dynamometer.getPulpNumber();
            } else if (tishTime > endTime) {
                if ((tishTime - endTime) < (endTime - lengthTime)) {
                    size++;
                    mileage = dynamometer.getMileage();
                    propellerFrequencyTotal += Integer.parseInt(dynamometer.getPropellerFrequency());
                    heartRateTotal += dynamometer.getHeartRate();
                    lengthTime = tishTime;
                    powerTotal += StringUtils.turnSecond(dynamometer.getPower());
                    wattTotal += Integer.parseInt(dynamometer.getWatt());
                    peakForceTotal += dynamometer.getPeakForce();
                    averageForceTotal += dynamometer.getAverageForce();
                    pulpNumber = dynamometer.getPulpNumber();
                }
                break;
            }
        }
        if (size > 0) {
            ds = new DynamometerSubsection();
            ds.setMileage(mileage);
            ds.setPropellerFrequency(String.valueOf(propellerFrequencyTotal / size));
            ds.setHeartRate(heartRateTotal / size);
            ds.setLengthTime(StringUtils.millisecondRotationTime(lengthTime));
            double speed = (mileage - firstDistance) / (lengthTime - firstTime);
            ds.setSpeed(speed);
            ds.setPower(StringUtils.millisecondRotationTime(powerTotal / size));
            ds.setWatt(String.valueOf(wattTotal / size));
            ds.setPeakForce(peakForceTotal / size);
            ds.setAverageForce(averageForceTotal / size);
            ds.setPulpNumber(pulpNumber);
        }

        return ds;
    }

    /**
     * 根据实时数据计算出分段(距离手段)
     *
     * @param list
     * @param endDistance
     * @return
     */
    private DynamometerSubsection calculationDynamometerSubsection(List<Dynamometer> list, int startDistance, int endDistance) {
        DynamometerSubsection ds = null;
        double mileage = 0.0;//里程
        int propellerFrequencyTotal = 0;//浆频
        int heartRateTotal = 0;//心率
        long lengthTime = 0;//时长
        long powerTotal = 0;//功率
        long firstTime = 0;//第一个有效的点时间
        double firstDistance = 0;//第一个有效的点距离
        int wattTotal = 0;//瓦特
        double peakForceTotal = 0;//峰力
        double averageForceTotal = 0;//均力
        int pulpNumber = 0;//浆数
        int size = 0;
        for (Dynamometer dynamometer : list) {
            if (StringUtils.isEmpty(dynamometer.getPropellerFrequency()) || dynamometer.getPropellerFrequency().equals("0")) {
                continue;
            }
            long tishTime = StringUtils.turnSecond(dynamometer.getLengthTime());
            double distance = dynamometer.getMileage();
            if (distance >= startDistance && distance <= endDistance) {
                if (firstTime == 0) {
                    firstTime = tishTime;
                    firstDistance = distance;
                }
                size++;
                mileage = dynamometer.getMileage();
                propellerFrequencyTotal += Integer.parseInt(dynamometer.getPropellerFrequency());
                heartRateTotal += dynamometer.getHeartRate();
                lengthTime = tishTime;
                powerTotal += StringUtils.turnSecond(dynamometer.getPower());
                wattTotal += Integer.parseInt(dynamometer.getWatt());
                peakForceTotal += dynamometer.getPeakForce();
                averageForceTotal += dynamometer.getAverageForce();
                pulpNumber = dynamometer.getPulpNumber();
            } else if (distance > endDistance) {
                if ((distance - endDistance) < (endDistance - mileage)) {
                    size++;
                    mileage = dynamometer.getMileage();
                    propellerFrequencyTotal += Integer.parseInt(dynamometer.getPropellerFrequency());
                    heartRateTotal += dynamometer.getHeartRate();
                    lengthTime = tishTime;
                    powerTotal += StringUtils.turnSecond(dynamometer.getPower());
                    wattTotal += Integer.parseInt(dynamometer.getWatt());
                    peakForceTotal += dynamometer.getPeakForce();
                    averageForceTotal += dynamometer.getAverageForce();
                    pulpNumber = dynamometer.getPulpNumber();
                }
                break;
            }
        }
        if (size > 0) {
            ds = new DynamometerSubsection();
            ds.setMileage(mileage);
            ds.setPropellerFrequency(String.valueOf(propellerFrequencyTotal / size));
            ds.setHeartRate(heartRateTotal / size);
            ds.setLengthTime(StringUtils.millisecondRotationTime(lengthTime));
            double speed = (mileage - firstDistance) / ((lengthTime - firstTime) / 1000.0);//速度
            ds.setSpeed(speed);
            ds.setPower(StringUtils.millisecondRotationTime(powerTotal / size));
            ds.setWatt(String.valueOf(wattTotal / size));
            ds.setPeakForce(peakForceTotal / size);
            ds.setAverageForce(averageForceTotal / size);
            ds.setPulpNumber(pulpNumber);
        }

        return ds;
    }

}
